package com.aispeech.asr.comm.etcd;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;

import java.util.Properties;

@Slf4j
public class EtcdEnvironmentPostProcessor implements EnvironmentPostProcessor {
    private static final String ETCD_CONFIG_IDENTIFYER = "ETCD_CONFIG";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication application) {
        Properties properties = readPropertiesByEnvironment();

        if (properties != null) {
            PropertiesPropertySource propertySource = new PropertiesPropertySource(ETCD_CONFIG_IDENTIFYER, properties);
            env.getPropertySources().addFirst(propertySource);
        }

    }

    private Properties readPropertiesByEnvironment() {
        Properties properties = null;

        String etcdServerLists = System.getenv("ETCD_SERVER_INTERNAL");

        if (StringUtils.isNotEmpty(etcdServerLists)) {
            try {
                properties = EtcdConfigClient.loadEtcdConfig(etcdServerLists);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

            if (properties == null)
                throw new RuntimeException(String.format("Failed read Etcd config from: %s", etcdServerLists));
        }

        return properties;
    }
}
